package cn.com.xy.sms.sdk.db.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.DBManager;
import cn.com.xy.sms.sdk.db.XyCursor;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.util.SdkParamUtil;

public class JarSubInfoManager {

	public static final int NOTFINISH = 0;
	public static final int FINISH = 1;
	
	public static final String ID = "id";  
	public static final String NAME = "name";
	public static final String VERSION = "version";
	public static final String URL = "url";
	public static final String STATUS  ="status";//0未下载(包括还没下载完的)，1下载完毕	
	public static final String LASTLOADTIME = "last_load_time";
	public static final String UPDATETIME = "update_time";
	public static final String DELAYSTART = "delaystart";
	public static final String DELAYEND = "delayend";
	public static final String PVER = "pver";
	public static final String COUNT = "count";//更新次数
	public static final String TABLE_NAME = "tb_jar_list";
	public static final String IS_USE = "is_use";//是否已用0，为未用，1为已用
	
	public static final int USED = 1;
	public static final int NOT_USE = 0;//是否已用0，为未用，1为已用

	
	public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;
	public static final String CREATE_TABLE = "create table  if not exists "  + TABLE_NAME + " ("
														         + ID + " INTEGER PRIMARY KEY," 
																 + NAME+" TEXT,"
																 + VERSION +" TEXT,"
																 + URL +" TEXT,"
													             + STATUS+" INTEGER DEFAULT '0',"	
													             + UPDATETIME+" INTEGER DEFAULT '0',"
													             + DELAYSTART+" INTEGER DEFAULT '0',"	
													             + DELAYEND+" INTEGER DEFAULT '0',"
													             + COUNT+" INTEGER DEFAULT '0',"	
													             + LASTLOADTIME+" INTEGER DEFAULT '0' ,"
													             + IS_USE+" INTEGER DEFAULT '0' ,"
													              + PVER +" TEXT"
													             + ")";
	
	public static final String ADD_IS_USE = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+IS_USE+" INTEGER DEFAULT '0'";

	public static final String ADD_PVER = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+PVER+" TEXT ";

	
	//插入一个version为-1的jar
	public synchronized static void insertOrUpdateJarSubInfo(String name,String version,int isUse){
		
        XyCursor xyCursor = null;
        try {
        	
            xyCursor = DBManager.query(TABLE_NAME, new String[] {
                URL, VERSION
            }, NAME + " = ? ", new String[] {
            		name
            });
            ContentValues values = new ContentValues();            
            values.put(NAME, name);
           
            if(isUse==JarSubInfoManager.USED)
            {
            	 values.put(IS_USE, isUse);
            }
 			long rows =-1;
            if (xyCursor != null && xyCursor.getCount() > 0) {                 
     			if(!StringUtils.isNull(version)&&!"-1".equalsIgnoreCase(version)){
     				 values.put(VERSION, version);
     			}
     			rows =DBManager.update(TABLE_NAME, values, NAME + " = ? ", new String[] {
                		name
                });
            } else {
            	 values.put(VERSION, version);
                rows = DBManager.insert(TABLE_NAME,  values);
                 
                 //jar包不存在，需要插入数据到数据库。
            }
            
           if(rows > 0 && name.startsWith("PU")){
        	   //清理当前情景的缓存数据
        	  name = name.replaceFirst("PU", "");
        	  if(name.length() >= 8){
        		 name= name.substring(0,8);
//        		 LogManager.d("JarSubInfo", "deleteMatchCache sceneId: ",name);
        		 //升级无需，清除历史已识别过的数据。需要清除走立即招回指令。
//        		 MatchCacheManager.deleteMatchCache(name, System.currentTimeMillis());
        	  }
           }
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "insertOrUpdateJarSubInfo: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(xyCursor, true);
        }

    
	}
	
	public static String getJarMaxPver(){
		XyCursor cursor =null;
		String pver ="";
		try {			
			String where= "STATUS = 1 order by pver desc LIMIT 1 ";
			cursor =DBManager.query(TABLE_NAME,new String[]{"pver"}, where, null);		
			 if (cursor != null && cursor.getCount() > 0)
			 {
				 while(cursor.moveToNext()){
					 pver = cursor.getString(0);
					}
			 }	
			 String inner = SdkParamUtil.getParamValue(Constant.getContext(), Constant.SMART_ALGORITHM_PVER);
			 if(StringUtils.isNull(pver)){
				 return inner;
			 }
			 
			 if(!StringUtils.isNull(inner)&&inner.compareTo(pver)>0){
				 pver = inner;
			 }
			 
		}catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.e(Constant.TAG, "getJarMaxPver: ", e);
            /*SDK-550 hewengao 20160719 end*/
		}finally{
			XyCursor.closeCursor(cursor, true);
		}
		return pver;
	}
	
	/*public static void updateJarPver(String pver){
		try {
			if(StringUtils.isNull(pver)) return;
			ContentValues values = new ContentValues(); 
			String where= "pver < ? or pver is null";
	        values.put(PVER, pver);
			DBManager.update(TABLE_NAME, values, where, new String[] {pver});
		} catch (Throwable e) {
            LogManager.e(Constant.TAG, "updateJarPver: " + e.getMessage(), e);

		}
	}*/
	
	 public static JarSubInfo queryJarSubInfo(String name) {
	        XyCursor cur = null;
	        try {  cur = DBManager.query(TABLE_NAME, new String[] {
	                ID, NAME,VERSION,URL,STATUS, LASTLOADTIME,UPDATETIME,DELAYSTART,DELAYEND,COUNT
	            }, NAME + " = ? ", new String[] {name});
	            if (cur != null && cur.getCount() > 0) {
	                int idIndex = cur.getColumnIndex(ID);
	                int nameIndex = cur.getColumnIndex(NAME);
	                int versionIndex =  cur.getColumnIndex(VERSION);
	                int urlIndex = cur.getColumnIndex(URL);
	                int statusIndex = cur.getColumnIndex(STATUS);
	                int lastLoadTimeIndex = cur.getColumnIndex(LASTLOADTIME);
	                int udpateTimeIndex = cur.getColumnIndex(UPDATETIME);
	                int startIndex = cur.getColumnIndex(DELAYSTART);
	                int endIndex = cur.getColumnIndex(DELAYEND);
	                int countIndex = cur.getColumnIndex(COUNT);
	                JarSubInfo jarSubInfo = null;
	                while (cur.moveToNext()) {
	                	jarSubInfo = new JarSubInfo();
	                	jarSubInfo.id = cur.getLong(idIndex);
	                	jarSubInfo.name = cur.getString(nameIndex);
	                	jarSubInfo.version = cur.getString(versionIndex);
	                	jarSubInfo.url = cur.getString(urlIndex);
	                	jarSubInfo.status = cur.getInt(statusIndex);
	                	jarSubInfo.lastLoadTime = cur.getLong(lastLoadTimeIndex);
	                	jarSubInfo.updateTime = cur.getLong(udpateTimeIndex);        
	                	jarSubInfo.delaystart = cur.getLong(startIndex);
	                	jarSubInfo.delayend = cur.getLong(endIndex);
	                	jarSubInfo.count = cur.getInt(countIndex);
	                    return jarSubInfo;
	                }

	            }} catch (Throwable e) {
//	            e.printStackTrace();
	                /*SDK-550 hewengao 20160719 start*/
	                LogManager.e(Constant.TAG, "queryJarSubInfo: ", e);
	                /*SDK-550 hewengao 20160719 end*/
	        } finally {
	            XyCursor.closeCursor(cur, true);
	        }
	        return null;
	    }

    /* SDK-579 huangzhiqiang 20160805 start */
    /**
     * 获取所有使用过的Jar包数据
     * 
     * @return
     */
    public static List<JarSubInfo> queryAllJarSubInfo() {
        return queryIsUseJarSubInfoByUpdateTime(Long.MAX_VALUE);
    }

    /**
     * 获取小于指定更新时间的已使用过的Jar包数据
     * 
     * @param updateTime
     * @return
     */
    public static List<JarSubInfo> queryIsUseJarSubInfoByUpdateTime(long updateTime) {
        return queryJarSubInfo(new String[] { ID, NAME, VERSION, URL, STATUS, LASTLOADTIME, UPDATETIME, DELAYSTART,
                DELAYEND, COUNT }, "(" + IS_USE + " = ? or " + NAME + " = ? ) AND length(" + NAME + ") > 7  AND "
                + UPDATETIME + " < ?",
                /*SDK-634 20161009 songzhirong  start*/
                new String[] { String.valueOf(USED), "parseUtilMain", String.valueOf(updateTime) },"name desc");
                /*SDK-634 20161009 songzhirong  end*/
 
    }

    /**
     * 获取需要下载的算法包信息
     * 
     * @return
     */
    public static List<JarSubInfo> queryNeedDownloadJarInfo() {
        return queryJarSubInfo(new String[] { ID, NAME, VERSION, URL, STATUS, LASTLOADTIME, UPDATETIME, DELAYSTART,
                DELAYEND, COUNT }, IS_USE + " = 1 AND length(" + NAME + ") > 7  AND " + URL + " IS NOT NULL AND " + URL
                /*SDK-634 20161009 songzhirong  start*/
                + " <> '' AND " + STATUS + " = 0", null,"name desc");
                /*SDK-634 20161009 songzhirong  end*/
    }

    /**
     * 根据条件获Jar包数据
     * 
     * @return
     */
    public static List<JarSubInfo> queryJarSubInfo(String[] columns, String selection, String[] selectionArgs,String orderBy) {
        List<JarSubInfo> jarSubInfoList = null;
        XyCursor cur = null;
        try {
            /*SDK-634 20161009 songzhirong  start*/
            cur = DBManager.query(TABLE_NAME, columns,selection,selectionArgs, null,null,orderBy,null);           
            /*SDK-634 20161009 songzhirong  end*/
            jarSubInfoList = createJarSubInfoList(cur);
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "queryJarSubInfo error", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return jarSubInfoList;
    }


    private static List<JarSubInfo> createJarSubInfoList(XyCursor cur) {
        if (cur == null || cur.getCount() == 0) {
            return null;
        }
        List<JarSubInfo> jarSubInfoList = new ArrayList<JarSubInfo>();
        int idIndex = cur.getColumnIndex(ID);
        int nameIndex = cur.getColumnIndex(NAME);
        int versionIndex = cur.getColumnIndex(VERSION);
        int urlIndex = cur.getColumnIndex(URL);
        int statusIndex = cur.getColumnIndex(STATUS);
        int lastLoadTimeIndex = cur.getColumnIndex(LASTLOADTIME);
        int udpateTimeIndex = cur.getColumnIndex(UPDATETIME);
        int startIndex = cur.getColumnIndex(DELAYSTART);
        int endIndex = cur.getColumnIndex(DELAYEND);
        int countIndex = cur.getColumnIndex(COUNT);
        JarSubInfo jarSubInfo = null;
        while (cur.moveToNext()) {
            jarSubInfo = new JarSubInfo();
            jarSubInfo.id = cur.getLong(idIndex);
            jarSubInfo.name = cur.getString(nameIndex);
            jarSubInfo.version = cur.getString(versionIndex);
            jarSubInfo.url = cur.getString(urlIndex);
            jarSubInfo.status = cur.getInt(statusIndex);
            jarSubInfo.lastLoadTime = cur.getLong(lastLoadTimeIndex);
            jarSubInfo.updateTime = cur.getLong(udpateTimeIndex);
            jarSubInfo.delaystart = cur.getLong(startIndex);
            jarSubInfo.delayend = cur.getLong(endIndex);
            jarSubInfo.count = cur.getInt(countIndex);
            jarSubInfoList.add(jarSubInfo);
        }
        return jarSubInfoList;
    }
    /* SDK-579 huangzhiqiang 20160805 end */

    public static HashMap<String, String> queryAllJarInfoMap() {
        HashMap<String, String> allJarInfoMap = new HashMap<String, String>();
        XyCursor cur = null;
        try {
            cur = DBManager.query(TABLE_NAME, new String[] { NAME, VERSION }, null, null);
            if (cur != null && cur.getCount() > 0) {
                int nameIndex = cur.getColumnIndex(NAME);
                int versionIndex = cur.getColumnIndex(VERSION);
                while (cur.moveToNext()) {
                    allJarInfoMap.put(cur.getString(nameIndex), cur.getString(versionIndex));
                }
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "queryAllJarInfoMap: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return allJarInfoMap;
    }
	
	public static void updateLastLoadTime(String name,int status){
		try {
			long time = System.currentTimeMillis();
			ContentValues values = new ContentValues();
			values.put(LASTLOADTIME, time+"");
			values.put(STATUS, status+"");
			DBManager.update(TABLE_NAME, values, NAME+" = ? ", new String[]{name});
			
			SdkParamUtil.setParamValue(Constant.getContext(), Constant.SMART_DATA_UPDATE_TIME, time+"");
			
		} catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "updateLastLoadTime: ", e);
            /*SDK-550 hewengao 20160719 end*/
		}
	}
	public static void updateTime(String name,long delayStart,long delayend){
		try {
			ContentValues values = new ContentValues();
			values.put(UPDATETIME, System.currentTimeMillis()+"");
			values.put(DELAYSTART, delayStart+"");
			values.put(DELAYEND, delayend+"");
			DBManager.update(TABLE_NAME, values, NAME+" = ? ", new String[]{name});
		} catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "updateTime: ", e);
            /*SDK-550 hewengao 20160719 end*/
		}
	}
	
	public static void updateTime(String name){
		try {
			ContentValues values = new ContentValues();
			values.put(UPDATETIME, System.currentTimeMillis()+"");
			
			DBManager.update(TABLE_NAME, values, NAME+" = ? ", new String[]{name});
		} catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "updateTime: ", e);
            /*SDK-550 hewengao 20160719 end*/
		}
	}
	
	public static void updateCount(String name,int count){
		try {
			ContentValues values = new ContentValues();
			values.put(COUNT, count+1);
			
			DBManager.update(TABLE_NAME, values, NAME+" = ? ", new String[]{name});
		} catch (Throwable e) {
//			e.printStackTrace();
            LogManager.w(Constant.TAG, "updateCount: ", e);

		}
	}

	 
	public static void updateJarSubInfo(String name,String vesion,String url,long updateTime,int status,long delayStart,long delayend,String pver){
			try {
				ContentValues values = new ContentValues();
				values.put(VERSION, vesion);
				values.put(URL, url);
				values.put(STATUS, status);
				values.put(UPDATETIME, updateTime+"");
				values.put(DELAYSTART, delayStart+"");
				values.put(DELAYEND, delayend+"");
				values.put(PVER, pver);
				DBManager.update(TABLE_NAME, values, NAME+" = ? ", new String[]{name});
			} catch (Throwable e) {
//				e.printStackTrace();
			    /*SDK-550 hewengao 20160719 start*/
	            LogManager.w(Constant.TAG, "updateJarSubInfo: ", e);
	            /*SDK-550 hewengao 20160719 end*/
			}
	}
	

	/**
	 * 删除所有数据
	 * 
	 * @return
	 */
    public static int deleteAll() {
        try {
            return DBManager.delete(TABLE_NAME, null, null);
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteAll: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        return -1;
    }
    
    /**
     * 根据名称删除数据
     * 
     * @param name
     * @return
     */
    public static int deleteByName(String name) {
        try {
            if (StringUtils.isNull(name)) {
                return 0;
            }
            return DBManager.delete(TABLE_NAME, NAME + " = ?", new String[] { name });
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteByName: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        return -1;
    }
    
    /**
     * 根据名称删除数据
     * 
     * @param names
     * @return
     */
    public static int deleteByName(List<String> names) {
        try {
            if (names == null || names.size() == 0) {
                return 0;
            }
            StringBuilder sbrFilter = new StringBuilder();
            for (String name : names) {
                if(StringUtils.isNull(name)){
                    continue;
                }
                sbrFilter.append("'");
                sbrFilter.append(name.trim());
                sbrFilter.append("',");
            }
            if (sbrFilter.length() > 0) {
                // 去除结尾多出的逗号
                sbrFilter.setLength(sbrFilter.length() - 1);
                return DBManager.delete(TABLE_NAME, NAME + " IN (" + sbrFilter + ")", null);
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteByName: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        return -1;
    }
    
    /**
     * 删除老算法包数据
     * 
     * @return
     */
    public static int deleteOldJar(){
        List<String> oldJarNames = new ArrayList<String>();
        oldJarNames.add("ParseUtilCasual");
        oldJarNames.add("ParseUtilEC");
        oldJarNames.add("ParseUtilFinanceL");
        oldJarNames.add("ParseUtilFinanceM");
        oldJarNames.add("ParseUtilFinanceS");
        oldJarNames.add("ParseUtilLife");
        oldJarNames.add("ParseUtilMove");
        oldJarNames.add("ParseUtilTelecom");
        oldJarNames.add("ParseUtilTravel");
        oldJarNames.add("ParseUtilUnicom");
        return deleteByName(oldJarNames);
    }
 
    /**
     * 根据算法包名称获取默认的是否已使用值，当算法包名称为parseUtilMain、ParseHelper、ScenesScanner时返回已使用，否则返回未使用
     * 
     * @param parseName
     * @return
     */
    public static int getDefaultUsed(String parseName){
        if("parseUtilMain".equals(parseName) || "ParseHelper".equals(parseName) || "ScenesScanner".equals(parseName)){
            return USED;
        }
        return NOT_USE;
    }
    
    /**
     * 批量插入tb_jar_list，并删除重复数据
     * 
     * @param sqlList SELECT UNION ALL语句集合
     * @return
     */
    public static boolean insertJarSubInfo(List<String> sqlList){
        SQLiteDatabase db = null;
        try {
            db = DBManager.getSQLiteDatabase();
            db.beginTransaction();  
             
            StringBuilder sbrSqlText = new StringBuilder();
            sbrSqlText.append("INSERT INTO tb_jar_list(name,version,is_use) ");
            sbrSqlText.append("SELECT tempTb.name,tempTb.version,tempTb.is_use FROM (");
            sbrSqlText.append("SELECT tbA.name,ifnull((CASE WHEN ('-1'=tbA.version OR ''=tbA.version) ");
            sbrSqlText.append("THEN tbB.version ELSE tbA.version END),'-1')version,");
            sbrSqlText.append("ifnull((CASE WHEN 1=tbA.is_use THEN tbA.is_use ELSE tbB.is_use END),0)is_use FROM (");
            sbrSqlText.append("{SQL})tbA LEFT JOIN tb_jar_list tbB ON tbA.name=tbB.name)");
            sbrSqlText.append("tempTb LEFT JOIN tb_jar_list ON tb_jar_list.name = tempTb.name");
            String sqlText = sbrSqlText.toString();
            
            for (String insertSql : sqlList) {
                db.execSQL(sqlText.replace("{SQL}", insertSql));
            }

            return true;
        } catch (Throwable e) {
//            ex.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "insertJarSubInfo: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            if (db != null) {
                try {
                    // 删除重复数据
                    /* SDK-582 huangzhiqiang 20160905 start */
                    db.execSQL("DELETE FROM tb_jar_list WHERE id NOT IN (SELECT MAX(id) FROM tb_jar_list GROUP BY name)");
                    /* SDK-582 huangzhiqiang 20160905 end */
                } catch (Throwable e) {
                    /*SDK-550 hewengao 20160719 start*/
                    LogManager.w(Constant.TAG, "insertJarSubInfo: ", e);
                    /*SDK-550 hewengao 20160719 end*/
                }
                try {
                    if (db.inTransaction()) {
					    db.setTransactionSuccessful();
                        db.endTransaction();
                    }
                } catch (Throwable e) {
//                    e.printStackTrace();
                    /*SDK-550 hewengao 20160719 start*/
                    LogManager.w(Constant.TAG, "insertJarSubInfo: ", e);
                    /*SDK-550 hewengao 20160719 end*/

                }
                DBManager.close(db);
            }
        }
        return false;
    }
    
    /**
     * 是否需要更新算法包
     * 
     * @return
     */
    public static boolean needUpdateJar() {
        XyCursor cur = null;
        try {
          
            cur = DBManager.query(TABLE_NAME, new String[] { NAME }, "("
                    + IS_USE + " = ? or " + NAME + " = ? ) AND length(" + NAME
                    + ") > 7 AND " + STATUS + " = ? AND " + URL
                    + " IS NOT NULL AND " + URL + " <> '' ",
                    new String[] { String.valueOf(USED), "parseUtilMain",
                            String.valueOf(NOTFINISH) }, null, null, null,
                    " 1 ");
//            Log.i("xiaoyuan needUpdateJar", "cur="+cur+" count=" +(cur !=null ? cur.getCount() :"0"));
            if (cur != null && cur.getCount() > 0) {
                return true;
            }
        } catch (Throwable ex) {
//            Log.i("xiaoyuan needUpdateJar", "ex="+ex.getMessage());
//            ex.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w("JarSubInfoManager needUpdateJar", "判断是否需要更新算法包异常", ex);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cur, true);
        }
//        Log.i("xiaoyuan needUpdateJar", "return false");
        return false;
    }
    /*ONEPLUSCII-98 songzhirong 20161226 start*/
    public static void updateIsUse(String name,int isUse){
		try {
			ContentValues values = new ContentValues();
			values.put(IS_USE, isUse);			
			DBManager.update(TABLE_NAME, values, NAME+" = ? ", new String[]{name});
		} catch (Throwable e) {
//			e.printStackTrace();
            LogManager.w(Constant.TAG, "updateIsUse: ", e);

		}
	}
    /*ONEPLUSCII-98 songzhirong 20161226 end*/
}
